package com.shuoyue.ycgk.ui.common;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.ui.common.download.AndroidBug5497Workaround;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 拼团规则
 * Forty'7
 */
@SuppressLint("SetJavaScriptEnabled")
public class CstWebActivity extends BaseMvpActivity {

    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.content)
    FrameLayout content;
    private static final int FILECHOOSER_RESULTCODE = 1;
    public static final int REQUEST_SELECT_FILE = 100;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> uploadMessage; // 用于5.0以上
    public static void start(Context context, String url, String title) {
        context.startActivity(new Intent(context, CstWebActivity.class)
                .putExtra("downloadUrl", url)
                .putExtra("title", title)
        );

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CstWebActivityUtil.assistActivity(this);
//        AndroidBug5497Workaround.assistActivity(this, content);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_cst_web;
    }

    @Override
    protected void initView() {
        String url = getIntent().getStringExtra("downloadUrl");
        String title = getIntent().getStringExtra("title");
//        pageTitle.setText(title);
        initWebView(webview);
        webview.loadUrl(url);
    }

    @Override
    public void initData() {

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webview.canGoBack()) {
                webview.goBack();
            } else {
                finish();
            }
        }

        return super.onKeyDown(keyCode, event);

    }


    public void initWebView(WebView mWebView) {
        //WebView 获取设置
        //webView 设置属性
        mWebView.clearCache(true);
        webview.addJavascriptInterface(this, "fhy");
        webview.setScrollContainer(true);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setUseWideViewPort(true);
        //将图片调整到适合webview的大小
        webSettings.setSupportZoom(false);//支持缩放
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容从新布局
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//关闭webview中缓存
        webSettings.setLoadsImagesAutomatically(true);//支持自动加载图片
        webSettings.setJavaScriptEnabled(true);
//        webSettings.setBuiltInZoomControls(false);// 隐藏缩放按钮
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        webSettings.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。
        webSettings.setAppCacheEnabled(true);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_INSET);
        webSettings.setDomStorageEnabled(true);

        mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {

            }

        });
        WebViewClient wvc = new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("用户单击超连接", url);
                return super.shouldOverrideUrlLoading(view, url);
            }
            /**
             * {@inheritDoc}
             * 安卓3.0-
             */
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooser(uploadMsg, "");
            }

            /**
             * {@inheritDoc}
             * 安卓3.0 - 4.0
             */
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = null;
                if (Build.VERSION.SDK_INT < 19) {
                    i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.setType("image/*");
                } else {
                    i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }
                startActivityForResult(Intent.createChooser(i, "选择图片"), FILECHOOSER_RESULTCODE);
            }

            /**
             * {@inheritDoc}
             * 安卓 4.0 - 5.0
             */
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooser(uploadMsg, acceptType);
            }

            /**
             *  安卓5.0+
             */
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;

                Intent intent = fileChooserParams.createIntent();
                try {
                    startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_SELECT_FILE);
                } catch (ActivityNotFoundException e) {
                    uploadMessage = null;
                    Toast.makeText(getApplicationContext(), "文件上传失败", Toast.LENGTH_LONG).show();
                    return false;
                }
                return true;
            }
        };
        mWebView.setWebViewClient(wvc);
    }

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    void goback() {
        back();
    }

    @Override
    public void onBackPressed() {
        back();
    }

    void back() {
        if (webview.canGoBack()) {
            webview.goBack();
        } else {
            finish();
        }
    }


    @OnClick({R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                back();
                break;
//            case R.id.top:
//                webview.scrollTo(0, 0);
//                break;
        }
    }


    /**
     * 判断Uri是否有效
     */
    public boolean isValidIntent(Intent intent) {
        PackageManager packageManager = mContext.getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
        return !activities.isEmpty();
    }

    /**
     * 判断用户是否安装QQ客户端
     */
    public boolean isQQClientAvailable() {
        final PackageManager packageManager = mContext.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case FILECHOOSER_RESULTCODE:
                case REQUEST_SELECT_FILE:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        if (requestCode == REQUEST_SELECT_FILE) {
                            if (uploadMessage == null)
                                return;
                            Uri result = (data == null || resultCode != RESULT_OK) ? null : data.getData();
                            if (result != null) {
                                uploadMessage.onReceiveValue(new Uri[]{result});
                            } else {
                                uploadMessage.onReceiveValue(new Uri[]{});
                            }
                            uploadMessage = null;
                        }
                    } else if (requestCode == FILECHOOSER_RESULTCODE) {
                        if (null == mUploadMessage)
                            return;
                        Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                        Uri uri = Uri.fromFile(new File(getImagePath(result)));
                        mUploadMessage.onReceiveValue(uri); // 转换后
                        mUploadMessage = null;
                    } else
                        Toast.makeText(getApplicationContext(), "文件上传失败", Toast.LENGTH_LONG).show();
                    break;
                case 10:
                case 11:
                    String path = data.getStringExtra("path");
                    //TODO
//                    upFile(path);
                    break;
            }
        }
    }

    // 根据图片的Uri得到图片的路径
    private String getImagePath(Uri originalUri) {
        String[] pro = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(originalUri, pro, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        return path;
    }
}
